import React, {useState, useEffect} from 'react';
import './SideMenu.css';
import axios from "axios";
import {withRouter} from 'react-router-dom';
import {Layout, Menu} from 'antd';
import {connect} from "react-redux";
import {
    UserOutlined,
} from '@ant-design/icons';

const {Sider} = Layout;
const {SubMenu} = Menu;

// 动态侧边栏数据
// const MenuList = [
//     {
//         // 使用路径做key值，既有唯一性，又可以方便跳转
//         key: '/home',
//         title: '首页',
//         icon: <UserOutlined />
//     },
//     {
//         key: '/user-manage',
//         title: '用户管理',
//         icon: <UserOutlined />,
//         children: [
//             {
//                 key: '/user-manage/list',
//                 title: '用户列表',
//                 icon: <UserOutlined />,
//             }
//         ]
//     },
//     {
//         key: '/right-manage',
//         title: '权限管理',
//         icon: <UserOutlined />,
//         children: [
//             {
//                 key: '/right-manage/role/list',
//                 title: '角色列表',
//                 icon: <UserOutlined />,
//             },
//             {
//                 key: '/right-manage/right/list',
//                 title: '权限列表',
//                 icon: <UserOutlined />,
//             },
//         ]
//     },
// ]

// 动态侧边栏icon
const iconList = {
    '/home': <UserOutlined/>,
    '/user-manage': <UserOutlined/>,
    '/user-manage/list': <UserOutlined/>,
    '/right-manage': <UserOutlined/>,
    '/right-manage/role/list': <UserOutlined/>,
    '/right-manage/right/list': <UserOutlined/>,
    // ....
}

function SideMenu(props) {

    const [menu,setMenu] = useState([])

    const {role:{rights}} = JSON.parse(localStorage.getItem('token'))

    useEffect(() => {
        axios.get('/rights?_embed=children').then(res => {
            // console.log(res.data)
            setMenu(res.data)
        })
    },[])

    // 判断 pagepermisson 是否为1，从而判断是否需要渲染到侧边栏菜单
    const checkPagePermisson = (item) => {
        // rights.includes(item.key)：判断当前用户的权限列表中是否包含该项
        return item.pagepermisson === 1 && rights.includes(item.key)
    }

    // 菜单渲染函数
    const renderMenu = (MenuList) => {
        return MenuList.map(item => {

            // 加 ？是因为递归时的第二层没有 children ，如果还 .length 就会出错，所以需要先判断是否有 children
            if (item.children?.length>0 && checkPagePermisson(item)) {
                // 折叠菜单
                return <SubMenu key={item.key} icon={iconList[item.key]} title={item.title}>
                    {/* 使用递归函数：简化代码 */}
                    {renderMenu(item.children)}
                </SubMenu>
            }
            return checkPagePermisson(item) && <Menu.Item key={item.key} icon={iconList[item.key]} onClick={() => {
                props.history.push(item.key)
            }}>{item.title}</Menu.Item>
        })
    }

    const unexpectedHighlight = (value) => {
        let secondRouter = value.split('/')[2]
        if (secondRouter === 'update'){
            return '/news-manage/draft'
        }else {}
        return value
    }

    const selectedKeys = [unexpectedHighlight(props.location.pathname)]
    const openKeys = ['/'+props.location.pathname.split('/')[1]]

    return (
        <Sider trigger={null} collapsible collapsed={props.collapsed} className='noselect'>
            {/* 局部滚动条 */}
            <div style={{display:'flex', height:'100%', flexDirection:'column'}}>
                <div className="logo">全球新闻发布系统</div>
                <div style={{flex:1, overflow: 'auto'}}>
                    {/* selectedKeys: 初始选中的菜单项 key 数组;   openKeys：初始展开的 SubMenu 菜单项 key 数组 */}
                    <Menu theme="dark" mode="inline" selectedKeys={selectedKeys} defaultOpenKeys={openKeys}>    {/* 使用 defaultSelectedKeys: 非受控组件->虽然外面相关数据发生了改变，但该组件里面数据不会随之发生改变。 selectedKeys：受控组件 */}
                        {/* 使用函数渲染菜单 */}
                        {renderMenu(menu)}
                    </Menu>
                </div>
            </div>
        </Sider>
    )
}

const mapStateToProsp = (state) => {
    return {
        collapsed: state.CollapsedReducer.collapsed
    }
}


// withRouter使 props 直接获取 history 等方法
export default connect(mapStateToProsp)(withRouter(SideMenu))